package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.ProductBean;
import com.project.bean.SellBean;
import com.project.bean.SellCarBean;
import com.project.mapper.IProductMapper;
import com.project.mapper.ISellCarMapper;
import com.project.mapper.ISellInfoMapper;
import com.project.mapper.ISellMapper;
import com.project.service.ISellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
@Service
@Transactional
public class SellServiceImpl implements ISellService {
    @Autowired
    private ISellMapper sellMapper;
    @Autowired
    private ISellCarMapper sellCarMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;
    @Autowired
    private IProductMapper productMapper;
    @Override
    public void addOrder(Integer userId, SellBean sellBean) {
        //计算总价
        Integer totalPrice = sellCarMapper.getTotalPage(userId);
        sellBean.setTotalPrice(totalPrice);

        System.out.println(sellBean);
        //保存订单
        sellMapper.insert(sellBean);

        //查询用户购物信息
        QueryWrapper<SellCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);

        List<SellCarBean> sellCarList = sellCarMapper.selectList(qw);

        //循环添加订单明细
        sellInfoMapper.addInfo(sellBean.getId(),sellCarList);

        for (SellCarBean carBean : sellCarList
        ) {
            ProductBean product = productMapper.selectById(carBean.getProductId());
            product.setNum(product.getNum() - carBean.getNum());

            productMapper.updateById(product);
        }
        //清空购物车
        sellCarMapper.delete(qw);
}

    @Override
    public IPage<SellBean> findByItem(Integer pageNO, String customerName, LocalDate startDate, LocalDate endDate) {
        return sellMapper.findByItem(new Page(pageNO,3),customerName,startDate,endDate);

    }


    @Override
    public SellBean findById(Integer id) {
        // 先查询销售订单订单对象（客户名称、销售员、销售日期、订单总金额、送货地址）
        SellBean sellBean = sellMapper.findById(id);
        //并且查询销售详情表中的关联数据（名称、品牌、成交价、销售数量）
        sellBean.setSellInfoList(sellInfoMapper.findList(id));

        return sellBean;
    }
}
